package main

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

//Pyaload

type MyClaim struct {
	Username string `json:"username"`
	jwt.StandardClaims
}

// secret签名
var mySignatureKey []byte = []byte("!@#qwe")

func main() {

	//实例化负载payload
	c := MyClaim{
		Username: "xiaoxu",
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix() + 60,  //JWT的生效时间
			ExpiresAt: time.Now().Unix() - 120, //签发JWT的过期时间
		},
	}

	//Header就是默认也是不用专门实例化
	/*
		{
			"alg": "HS256",
			"typ": "JWT"
		}
	*/

	//返回未加密signature
	sensitiveToken := jwt.NewWithClaims(jwt.SigningMethodHS256, c)

	//利用secret签名对token加密
	signature, err := sensitiveToken.SignedString(mySignatureKey)
	if err != nil {
		panic(err)
	}
	fmt.Println(signature)

	//解密Token
	token1, _ := jwt.ParseWithClaims(signature, &MyClaim{}, func(token *jwt.Token) (interface{}, error) {
		return mySignatureKey, nil
	})

	fmt.Println(token1)
	fmt.Println(token1.Claims)
	fmt.Println(token1.Claims.(*MyClaim).Username)
}
